package cn.jisol.ngame.actions;

import cn.jisol.ngame.actions.core.NAction;
import cn.jisol.ngame.actions.core.NActionEnum;
import cn.jisol.ngame.actions.core.NActionMethod;
import cn.jisol.ngame.actions.entity.TileServerInfo;
import cn.jisol.ngame.client.NClient;
import cn.jisol.ngame.proto.JNSyncMessage;

import java.util.*;

@NAction
public class TileSyncAction {


    //区块服务器列表{TileId:TileServerInfo}
    public static Map<Integer, List<TileServerInfo>> Tiles = new HashMap<>();


    @NActionMethod(NActionEnum.NAddTileServer)
    public static void NAddTileServer(JNSyncMessage.JNAddTileServer nTileServer, NClient client, Map<String, NClient> clients) {

        List<TileServerInfo> tileServerInfos = Tiles.get(nTileServer.getTile());
        if (Objects.isNull(tileServerInfos)) tileServerInfos = new ArrayList<>();
        tileServerInfos.add(
                TileServerInfo.builder()
                        .tile(nTileServer.getTile())
                        .server(client.getId())
                        .ip(nTileServer.getIp())
                        .port(nTileServer.getPort())
                        .master(nTileServer.getMaster())
                        .build()
        );

        //顺带给玩家发送添加区块服务器
        clients.forEach((k, v) ->{
            v.invoke(NActionEnum.NAddTileServer,nTileServer);
        });
    }

    @NActionMethod(NActionEnum.ServerClientDisconnect)
    public static void ServerClientDisconnect(NClient client,Map<String, NClient> clients) {

        //客户端断开连接，清理数据
        Tiles.values().forEach(tiles -> {
            tiles.removeIf(tileServerInfo -> tileServerInfo.getServer().equals(client.getId()));
        });

    }

    //获取最需要的TileId
    public static int getNeedTileId(){

        int need = 0;
        while (true){
            for (int i = 1; i <= 9; i++) {
                List<TileServerInfo> tileInfos = Tiles.get(i);
                if (Objects.isNull(tileInfos)) {
                    tileInfos = new ArrayList<>();
                    Tiles.put(i,tileInfos);
                }
                if (tileInfos.size() <= need) return i;
            }
            need++;
        }

    }

    public static TileServerInfo getTileInfoMaster(int index){
        List<TileServerInfo> tileInfos = Tiles.get(index);
        if (Objects.isNull(tileInfos)) {
            tileInfos = new ArrayList<>();
            Tiles.put(index,tileInfos);
        }
        for (TileServerInfo tileInfo : tileInfos) {
            if (tileInfo.isMaster()) return tileInfo;
        }
        return null;
    }

    public static List<TileServerInfo> getTileInfos(int index){
        return Tiles.getOrDefault(index,new ArrayList<>());
    }

}
